package com.example.hotel_lxy.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.GetUserBean;
import com.example.hotel_lxy.bean.ImgBean;
import com.example.hotel_lxy.bean.MyBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.sql.UserDao;
import com.example.hotel_lxy.ui.activity.LoginActivity;
import com.example.hotel_lxy.ui.activity.MainActivity;
import com.example.hotel_lxy.ui.activity.SetUpActivity;
import com.example.hotel_lxy.ui.activity.WebActivity;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.GlideEngine;
import com.example.hotel_lxy.utils.SPUtils;
import com.example.hotel_lxy.view.ImageViewPlus;
import com.example.hotel_lxy.view.UIndicator;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tmall.ultraviewpager.UltraViewPager;
import com.ysxsoft.common_base.base.BaseFragment;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

/***
 *
 * 我的
 *
 */
public class FragmentMy extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.vp_submit_info)
    UltraViewPager vpSubmitInfo;
    @BindView(R.id.ui_submit_info)
    UIndicator uiSubmitInfo;
    List<String> list_img = new ArrayList<>();

    @BindView(R.id.img_setup)
    ImageView imgSetup;
    @BindView(R.id.img_src)
    ImageViewPlus imgSrc;
    @BindView(R.id.my_name)
    TextView myName;
    @BindView(R.id.text_id)
    TextView textId;
    @BindView(R.id.text_tijiao)
    TextView textTijiao;
    @BindView(R.id.edit_content)
    EditText editContent;
    @BindView(R.id.edit_mobile)
    EditText editMobile;
    @BindView(R.id.text_agreement)
    TextView textAgreement;
    @BindView(R.id.text_privacy)
    TextView textPrivacy;
    @BindView(R.id.frame_gr)
    FrameLayout frameGr;
    @BindView(R.id.line1)
    LinearLayout line1;
    private UserDao demoDao;
    String nickname;
    @Override
    public int getLayoutId() {
        return R.layout.fragment_my_activity;
    }


    @Override
    protected void doWork(View view) {
        demoDao = new UserDao(getActivity());
        textAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        textAgreement.getPaint().setAntiAlias(true);//抗锯齿
        textPrivacy.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        textPrivacy.getPaint().setAntiAlias(true);//抗锯齿
        line1.setOnClickListener(this);
        textAgreement.setOnClickListener(this);
        textPrivacy.setOnClickListener(this);
        imgSetup.setOnClickListener(this);
        textTijiao.setOnClickListener(this);
        frameGr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showImg();
            }
        });
        String string = SPUtils.get(getActivity(), "names", "").toString();
        showDateMyMessage();
    }

    private void showImg() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .selectionMode(100)
                .maxSelectNum(1)
                .isEnableCrop(true)
                .previewImage(true)
                .circleDimmedLayer(true)
                .showCropFrame(false)
                .isZoomAnim(false)
                .showCropGrid(false)
                .scaleEnabled(true)
                .rotateEnabled(false)
                .withAspectRatio(7, 7)
                .compress(true)//图片是否压缩
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
        public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
        if (localMedia != null && localMedia.size() != 0) {
            String realPath = localMedia.get(0).getCompressPath();
            showImgview(realPath);
        }

    }

    private void showImgview(String path) {
        Log.e("TAG", "" + path);

        PostFormBuilder builder = OkHttpUtils.post()
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("flag", SPUtils.get(getContext(), "token", "").toString())
                .url(Api.POSY_UPLOADS);
        if (path != null && !path.isEmpty()) {
            File file = new File(path);
            builder.addFile("file[]", file.getName(), file);
        }
        showLoadingDialog();
        builder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                Log.e("TAG", "合同图片onResponse~~~~~~~~    " + response);
                ImgBean imgBean = JsonUtils.parseByGson(response, ImgBean.class);
                StringBuffer sb = new StringBuffer();
                if (imgBean.getCode().equals("0")) {
                    String id1 = imgBean.getData().get(0).getId();

                    showAddDate(id1,imgBean.getData().get(0).getUrl());
                }
            }
        });
    }

    private void showAddDate(String avatar,String url) {
        String token = SPUtils.get(getContext(), "token", "").toString();
        OkHttpUtils.post()
                .url(Api.POST_USER_AVATAR)
                .addHeader("flag", token)
                .addParams("avatar", avatar)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "添加头像onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "添加头像onResponse   " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            Glide.with(getActivity()).load(url).into(imgSrc);
                            String string = SPUtils.get(getContext(), "names", "").toString();
                            Log.e("TAG",string);
                            demoDao.updateavatar(SPUtils.get(getContext(), "names", "").toString(), url);
                            showDateMyMessage();
                        } else if (beanBean.getCode().equals("4")) {
                            SPUtils.put(getContext(), "token", "");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
        showDateMyMessages();
    }

    private void showDateMyMessage() {
//                     .addHeader("flag",token)
        String token = SPUtils.get(getContext(), "token", "").toString();
//        showLoadingDialog("请求中");
        OkHttpUtils.post()
                .url(Api.POST_INDEX)
                .addHeader("flag", token)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "我的首页onResponse~~~~~~~~    " + e.getMessage());
//                        hideLoadingDialog();
                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        hideLoadingDialog();
                        Log.e("TAG", "我的首页onResponse~~~~~~~~    " + response);
                        MyBean myBean = JsonUtils.parseByGson(response, MyBean.class);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("4")) {
                            SPUtils.put(getContext(), "token", "");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        if (beanBean.getCode().equals("0")) {
//                            Glide.with(getActivity()).load(myBean.getData().getList().getAvatar()).into(imgSrc);
//                            myName.setText("" + SPUtils.get(getContext(), "username", "").toString());
//                             nickname = myBean.getData().getList().getNickname();
//                            textId.setText("ID: " + SPUtils.get(getContext(), "mobile", "").toString());
                            showDateUltraViewpaget(myBean.getData().getCarousel());
                        }
                    }
                });
    }

    private void showDateMyMessages() {
//                     .addHeader("flag",token)
        String token = SPUtils.get(getContext(), "token", "").toString();
//        showLoadingDialog("请求中");
        OkHttpUtils.post()
                .url(Api.POST_USER_GETUSER)
                .addHeader("flag", token)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "我的首页1onResponse~~~~~~~~    " + e.getMessage());
//                        hideLoadingDialog();
                    }

                    @Override
                    public void onResponse(String response, int id) {
//                        hideLoadingDialog();
                        Log.e("TAG", "我的首页1onResponse~~~~~~~~    " + response);
//                        MyBean myBean = JsonUtils.parseByGson(response, MyBean.class);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("4")) {
                            SPUtils.put(getContext(), "token", "");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        if (beanBean.getCode().equals("0")) {
                            GetUserBean getUserBean = JsonUtils.parseObject(response, GetUserBean.class);
                            Glide.with(getActivity()).load(getUserBean.getData().getList().getAvatar()).into(imgSrc);
                            myName.setText("" + getUserBean.getData().getList().getUsername());
                            String string = SPUtils.get(getActivity(), "names", "").toString();
                            textId.setText("ID: " + string);
                        }
                    }
                });
    }

    private void showDateUltraViewpaget(List<MyBean.CarouselBean> carousel) {
        if (carousel.size() != 0) {
            list_img.clear();
            for (int i = 0; i < carousel.size(); i++) {
                list_img.add(carousel.get(i).getImage());
            }
        } else {
            list_img.add("https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3271024615,3425336920&fm=26&gp=0.jpg");
            list_img.add("https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3271024615,3425336920&fm=26&gp=0.jpg");
            list_img.add("https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3271024615,3425336920&fm=26&gp=0.jpg");
        }
        DemoPagerAdapter hiPagerAdapter = new DemoPagerAdapter(getContext());
        vpSubmitInfo.setAdapter(hiPagerAdapter);
        uiSubmitInfo.attachToViewPager(vpSubmitInfo.getViewPager());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_setup:
                SetUpActivity.start();
                break;
            case R.id.text_tijiao:
                if (!DatePhotoUtils.isMobileNumber(editMobile.getText().toString())) {
                    ToastUtils.show(getContext(), "请输入正确手机号");
                    return;
                }
                if (editContent.getText().toString().equals("")) {
                    ToastUtils.show(getContext(), "请输入意见");
                    return;
                }
                if (editMobile.getText().toString().equals("")) {
                    ToastUtils.show(getContext(), "手机号不能为空");
                    return;
                }
                showOpinion();
                break;
            case R.id.text_agreement://协议
                WebActivity.start("http://api.luxiaoyi.vip/about/1.html", "用户协议");
                break;
            case R.id.text_privacy://隐私
                WebActivity.start("http://api.luxiaoyi.vip/about/2.html", "隐私协议");
                break;
            case R.id.line1:
                editContent.setFocusable(true);
                editContent.setFocusableInTouchMode(true);
                editContent.requestFocus();
                initInput();
                break;
        }
    }

    private void initInput() {
        InputMethodManager inputManager = (InputMethodManager)editContent.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(editContent, 0);
    }

    private void showOpinion() {
        String token = SPUtils.get(getContext(), "token", "").toString();
        showLoadingDialog();
        OkHttpUtils.post()
                .url(Api.POST_USER_OPINION)
                .addHeader("flag", token)
                .addParams("content", editContent.getText().toString())
                .addParams("mobile", editMobile.getText().toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "意见反馈Exception~~~~~~~~    " + e.getMessage());
                        showToast(e.getMessage());
                        hideLoadingDialog();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "意见反馈onResponse~~~~~~~~    " + response);
                        hideLoadingDialog();
                        BeanBean beanBean = JsonUtils.parseObject(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            editContent.setText("");
                            editMobile.setText("");
                            editMobile.clearFocus();
                            editContent.clearFocus();
                            ToastUtils.show(getActivity(), "感谢你的反馈意见");
                        } else if (beanBean.getCode().equals("4")) {
                            SPUtils.put(getContext(), "token", "");
                            Intent intent = new Intent(getContext(), LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        } else {
                            ToastUtils.show(getActivity(), beanBean.getMsg());
                        }

                    }
                });
    }

    /**
     * 轮播
     */
    public class DemoPagerAdapter extends PagerAdapter {
        private Context context;

        public DemoPagerAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return list_img.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(container.getContext()).inflate(R.layout.home_image_item, null);
            ImageView iv = linearLayout.findViewById(R.id.iv);
            linearLayout.setId(R.id.iv);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            Log.e("TAG", "图片  " + list_img.get(position));
            Glide.with(context).load(list_img.get(position)).into(iv);
            container.addView(linearLayout);
            return linearLayout;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            LinearLayout view = (LinearLayout) object;
            container.removeView(view);
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (hidden) {//不可见
           Log.e("TAG",hidden+" ");
        } else {//可见
            showDateMyMessages();
        }
    }
}